package fun._6742.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import fun._6742.exception.CustomException;
import fun._6742.interceptor.LoginInterceptor;
import fun._6742.mapper.AddressMapper;
import fun._6742.model.dataobject.AddressDO;
import fun._6742.model.enums.AddressStatusEnum;
import fun._6742.model.valueobject.AddressVO;
import fun._6742.model.valueobject.LoginUser;
import fun._6742.request.AddressRequest;
import fun._6742.service.AddressService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AddressSvcImpl extends ServiceImpl<AddressMapper, AddressDO> implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    /**
     * 新增收货地址
     *
     * @param addressRequest
     */
    @Override
    public void createAddress(AddressRequest addressRequest) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        AddressDO addressDO = AddressDO.builder()
                .userId(loginUser.getId())
                .createTime(new Date())
                .build();
        BeanUtil.copyProperties(addressRequest, addressDO);
        boolean hasDefault = false;

        if (addressRequest.getDefaultStatus() == AddressStatusEnum.DEFAULT_STATUS.getStatus()) {
//            TODO jpa改造
            AddressDO addressDO1 = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                    .eq("user_id", loginUser.getId())
                    .eq("default_status", AddressStatusEnum.DEFAULT_STATUS.getStatus()));
//            AddressDO addressDO1 = addressMapper.selectByIdAndDefaultStatus(loginUser.getId(), AddressStatusEnum.DEFAULT_STATUS.getStatus());
            if (addressDO1 != null) {
                addressDO.setDefaultStatus(AddressStatusEnum.COMMON_STATUS.getStatus());
                hasDefault = true;
            }
        }
        int res = addressMapper.insert(addressDO);
        log.info("create address:res:{},data:{}", res, addressDO);
        if (hasDefault) {
            throw new CustomException(HttpStatus.NOT_FOUND, "there is already a default address, so the new address won't be default");
        }
    }

    @Override
    public void delAddress(long id) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        int res = addressMapper.delete(new QueryWrapper<AddressDO>().eq("id", id).eq("user_id",loginUser.getId()));
        if (res == 0) {
            throw new CustomException(HttpStatus.NOT_FOUND, "(id = " + id + ") does not exist");
        }
        log.info("delAddress:res:{},id:{}", res, id);
    }

    @Override
    public List<AddressVO> findAllAddress() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
//        TODO 改造成page
        List<AddressDO> listOfDO = addressMapper.selectList(new QueryWrapper<AddressDO>().eq("user_id", loginUser.getId()));
        List<AddressVO> listOfVO = listOfDO.stream()
                .map((obj) -> {
                    AddressVO v = new AddressVO();
                    BeanUtil.copyProperties(obj, v);
                    return v;
                }).collect(Collectors.toList());
        return listOfVO;
    }

    @Override
    public void updateAddress(long addressId, AddressRequest addressRequest) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>().eq("id", addressId).eq("user_id", loginUser.getId()));
        if (addressDO == null) {
            throw new CustomException(HttpStatus.NOT_FOUND, "(id = " + addressId + ") does not exist");
        }
        BeanUtil.copyProperties(addressRequest, addressDO);
        updateById(addressDO);
    }

    @Override
    public AddressVO queryDetail(long id) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>().eq("id", id).eq("user_id", loginUser.getId()));
        if (addressDO == null) {
            throw new CustomException(HttpStatus.NOT_FOUND, "(id = " + id + ") does not exist");
        }
        AddressVO addressVO = new AddressVO();
        BeanUtil.copyProperties(addressDO, addressVO);
        return addressVO;
    }
}
